package com.rslai.base.tool.servertest.paramfilter;

import com.alibaba.fastjson.JSONObject;
import com.rslai.base.tool.servertest.util.Util;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;

public class StringParamFilter extends ParamFilter {
    private static final String PREFIX = "str:";
    String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    Random random = new Random();

    protected String doHandle(String param) {
        if (Util.isJson(param))
            return setStringParam(param);
        if (param.startsWith("str:")) {
            return generateString(param);
        }
        return param;
    }

    protected boolean support(String param) {
        return (param.startsWith("str:")) || (param.contains("str:"));
    }

    protected char getRandomStr() {
        int index = this.random.nextInt(this.base.length());
        return this.base.charAt(index);
    }

    private String generateString(String param) {
        String countStr = param.substring("str:".length());
        Integer count = Integer.valueOf(countStr);
        if (count.intValue() <= 0) return "";
        StringBuilder sb = new StringBuilder(count.intValue());
        for (int i = 0; i < count.intValue(); i++) {
            sb.append(getRandomStr());
        }
        return sb.toString();
    }

    private String setStringParam(String param) {
        Map map = null;
        try {
            map = (Map) JSONObject.parse(param);
        } catch (Exception e) {
            return param;
        }
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            if (((String) entry.getValue()).startsWith("str:")) {
                map.put(entry.getKey(), generateString((String) entry.getValue()));
            }
        }
        return JSONObject.toJSONString(map);
    }
}
